package com.ddl.controller.core;

import com.ddl.common.exception.ExceptionUtil;
import com.ddl.common.exception.ResultModel;
import com.ddl.service.IUserFriendService;
import com.ddl.service.UserService;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author: liyuxiang
 * @create: 2018-11-27
 */
@RestController
@RequestMapping(value = "/app/user")
public class UserLogOutController {

    private final static Logger logger = LoggerFactory.getLogger(UserLogOutController.class);


    @Autowired
    IUserFriendService iUserFriendService;

    @Autowired
    UserService userService;

    /**
     * 退出登录
     * @param request
     * @return
     */
    @CrossOrigin(origins = "*", maxAge = 3600)
    @RequestMapping(value = "/logOut")
    public ResultModel logOut(HttpServletRequest request) {
        try {
            String token = request.getHeader("token");
            return userService.logOut(token);
        } catch (Exception e) {
            logger.error("logOut fail", e);
            return ExceptionUtil.getMessageException(e);
        }
    }

    /**
     * 修改密码
     *
     * @param request
     * @return
     */
    @CrossOrigin(origins = "*", maxAge = 3600)
    @RequestMapping(value = "/updatePwd")
    public ResultModel updatePwd(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        try {
            int userId = Integer.parseInt(request.getHeader("userId"));
            String oldPwd = map.get("oldPsd").toString();
            String newPwd = map.get("password").toString();
            return userService.updatePwd(userId, oldPwd, newPwd);
        } catch (Exception e) {
            logger.error("logOut fail, map:{}", new Gson().toJson(map), e);
            return ExceptionUtil.getMessageException(e);
        }
    }

    /**
     * 好友搜索
     *
     * @param map
     * @param request
     * @return
     */
    @CrossOrigin(origins = "*", maxAge = 3600)
    @RequestMapping(value = "/search")
    public ResultModel searchFriend(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        String mobile = map.get("mobile").toString();
        return iUserFriendService.searchFriend(mobile);
    }
}
